package com.lyy.system.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyy.common.utils.*;
import com.lyy.common.utils.excel.ExcelUtils;
import com.lyy.common.utils.jxls.JxlsExport;
import com.lyy.system.pojo.SysWhitePhone;
import com.lyy.system.service.SysWhitePhoneService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * (SysWhitePhone)表控制层
 *
 * @author Yw
 * @since 2021-02-02 19:31:06
 */
@RestController
@RequestMapping("/sysWhitePhone")
public class SysWhitePhoneController {
    /**
     * 服务对象
     */
    @Resource
    private SysWhitePhoneService sysWhitePhoneService;

    /**
     * 创建
     * /sysWhitePhone/createSysWhitePhone
     * { "name":"姓名",  "delFlag":"删除状态，0否 1是" }
     *
     * @param name    姓名
     * @param delFlag 删除状态，0否 1是
     * @return
     */
    @PostMapping("/createSysWhitePhone")
    public Map<String, Object> createSysWhitePhone(SysWhitePhone sysWhitePhone) {
        AssertUtils.notNull(sysWhitePhone.getName(), "姓名不能为空");
        AssertUtils.notNull(sysWhitePhone.getDelFlag(), "删除状态，0否 1是不能为空");
        sysWhitePhoneService.createSysWhitePhone(sysWhitePhone);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 根据主键修改
     * /sysWhitePhone/updateSysWhitePhone
     * { "phone":"手机号码",  "name":"姓名",  "delFlag":"删除状态，0否 1是" }
     *
     * @param phone   手机号码
     * @param name    姓名
     * @param delFlag 删除状态，0否 1是
     * @return
     */
    @PutMapping("/updateSysWhitePhone")
    public Map<String, Object> updateSysWhitePhone(SysWhitePhone sysWhitePhone) {
        AssertUtils.notNull(sysWhitePhone.getPhone(), "手机号码不能为空");
        AssertUtils.notNull(sysWhitePhone.getName(), "姓名不能为空");
        AssertUtils.notNull(sysWhitePhone.getDelFlag(), "删除状态，0否 1是不能为空");
        sysWhitePhoneService.updateSysWhitePhone(sysWhitePhone);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 根据主键获取单个
     * /sysWhitePhone/getSysWhitePhone
     * { "phone":"手机号码" }
     *
     * @param phone 手机号码
     * @return
     */
    @GetMapping("/getSysWhitePhone")
    public Map<String, Object> getSysWhitePhone(SysWhitePhone sysWhitePhone) {
        AssertUtils.notNull(sysWhitePhone.getPhone(), "手机号码不能为空");
        SysWhitePhone entity = sysWhitePhoneService.getSysWhitePhone(sysWhitePhone);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sysWhitePhone", entity);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 根据主键删除
     * /sysWhitePhone/deleteSysWhitePhone
     * { "phone":"手机号码" }
     *
     * @param phone 手机号码
     * @return
     */
    @DeleteMapping("/deleteSysWhitePhone")
    public Map<String, Object> deleteSysWhitePhone(SysWhitePhone sysWhitePhone) {
        AssertUtils.notNull(sysWhitePhone.getPhone(), "手机号码不能为空");
        sysWhitePhoneService.deleteSysWhitePhone(sysWhitePhone);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 查询列表
     * /sysWhitePhone/selectSysWhitePhoneList
     * { "phone":"手机号码",  "name":"姓名",  "delFlag":"删除状态，0否 1是" }
     *
     * @param phone   手机号码
     * @param name    姓名
     * @param delFlag 删除状态，0否 1是
     * @return
     */
    @GetMapping("/selectSysWhitePhoneList")
    public Map<String, Object> selectSysWhitePhoneList(SysWhitePhone sysWhitePhone) {
        List<SysWhitePhone> sysWhitePhones = sysWhitePhoneService.selectSysWhitePhoneList(sysWhitePhone);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sysWhitePhones", sysWhitePhones);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }

    /**
     * 查询列表
     * /sysWhitePhone/selectSysWhitePhoneCount
     * { "phone":"手机号码", "name":"姓名", "delFlag":"删除状态，0否 1是"}
     *
     * @param phone   手机号码
     * @param name    姓名
     * @param delFlag 删除状态，0否 1是
     * @return
     */
    @GetMapping("/selectSysWhitePhoneCount")
    public Map<String, Object> selectSysWhitePhoneCount(SysWhitePhone sysWhitePhone) {
        int count = sysWhitePhoneService.selectSysWhitePhoneCount(sysWhitePhone);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("count", count);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 查询列表分页
     * /sysWhitePhone/selectSysWhitePhonePage
     * { "phone":"手机号码",  "name":"姓名",  "delFlag":"删除状态，0否 1是" ,"pageNum":"页码","pageSize":"条数"}
     *
     * @param pageNum  页码
     * @param pageSize 页数
     * @param phone    手机号码
     * @param name     姓名
     * @param delFlag  删除状态，0否 1是
     * @return
     */
    @GetMapping("/selectSysWhitePhonePage")
    public Map<String, Object> selectSysWhitePhonePage(SysWhitePhone sysWhitePhone, Integer pageNum, Integer pageSize) {
        AssertUtils.notNull(pageNum, "页码不能为空!");
        AssertUtils.notNull(pageSize, "条数不能为空!");
        PageHelper.startPage(pageNum, pageSize);
        List<SysWhitePhone> sysWhitePhones = sysWhitePhoneService.selectSysWhitePhoneList(sysWhitePhone);
        PageInfo<SysWhitePhone> pageInfo = new PageInfo<>(sysWhitePhones);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageInfo", pageInfo);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 导出
     * /sysWhitePhone/exportSysWhitePhoneExcel
     * { "phone":"手机号码",  "name":"姓名",  "delFlag":"删除状态，0否 1是" }
     *
     * @param phone   手机号码
     * @param name    姓名
     * @param delFlag 删除状态，0否 1是
     * @return
     */
    @GetMapping("/exportSysWhitePhoneExcel")
    public void exportSysWhitePhoneExcel(HttpServletRequest request, HttpServletResponse response, SysWhitePhone sysWhitePhone) {
        List<SysWhitePhone> sysWhitePhones = sysWhitePhoneService.selectSysWhitePhoneList(sysWhitePhone);
        if (CommonUtils.isNotEmpty(sysWhitePhones)) {
            List<String> titles = new ArrayList<>();
            titles.add(" 序号 ");
            titles.add(" 姓名 ");
            titles.add(" 删除状态，0否 1是 ");
            List<List<String>> values = new ArrayList<>();
            int k = 0;
            for (SysWhitePhone entity : sysWhitePhones) {
                List<String> value = new ArrayList<>();
                value.add((++k) + "");
                value.add(entity.getName());
                value.add(entity.getDelFlag());
                values.add(value);
            }
            String address = Constants.address + "/wisdom/template/customTemplate.xls";
            String excelName = "未命名.xls";
            Map<String, Object> beans = new HashMap<>();
            beans.put("titles", titles);
            beans.put("values", values);
            beans.put("date", DateUtils.formatDateTime(new Date()));
            JxlsExport.export(request, response, beans, excelName, address);
        }
    }

    /**
     * 根据主键逻辑删除
     * /sysWhitePhone/deleteSysWhitePhoneLogic
     * { "phone":"手机号码" }
     *
     * @param phone 手机号码
     * @return
     */
    @PutMapping("/deleteSysWhitePhoneLogic")
    public Map<String, Object> deleteSysWhitePhoneLogic(SysWhitePhone sysWhitePhone) {
        sysWhitePhone.setDelFlag("1");
        sysWhitePhoneService.updateSysWhitePhone(sysWhitePhone);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * /sysWhitePhone/importSysWhitePhoneExcel  从excel表导入
     * 导入excel文件
     * {"file":"excel文件"}
     *
     * @param file excel文件
     */
    @PostMapping("/importSysWhitePhoneExcel")
    public Map<String, Object> importSysWhitePhoneExcel(MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtils.getResult(ResultInfo.UPLOAD_NOT_EXISTS);
        }
        // 文件名称
        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return ResultUtils.getResult(ResultInfo.UPLOAD_NOT_EXISTS);
        }
        try {
            InputStream inputStream = file.getInputStream();
            //创建工作簿
            Workbook wb = null;
            //判断表格格式
            if (fileName.toLowerCase().endsWith("xls")) {
                wb = new HSSFWorkbook(inputStream);
            } else if (fileName.toLowerCase().endsWith("xlsx")) {
                wb = new XSSFWorkbook(inputStream);
            } else {
                return ResultUtils.getResult(ResultInfo.UPLOAD_TYPE_ERROR);
            }
            List<SysWhitePhone> sysWhitePhones = new ArrayList<>();
            List<Map<String, String>> resultMap = new ArrayList<>();
            Map<String, String> result = null;
            SysWhitePhone sysWhitePhone = null;
            // 获取工作表的第一个Sheet
            Sheet hssfSheet = wb.getSheetAt(0);
            if (hssfSheet != null) {
                int index = -1;
                for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow != null) {
                        if (ExcelUtils.getValue(hssfRow.getCell(0)).contains("姓名") &&
                                ExcelUtils.getValue(hssfRow.getCell(1)).contains("删除状态，0否 1是")) {
                            index = ++rowNum;
                            break;
                        }
                    }
                }

                if (index == -1) {
                    result = new HashMap<>();
                    result.put("reason", "excel模板不正确");
                    result.put("status", "1");
                    resultMap.add(result);
                    Map<String, Object> map = new HashMap<>();
                    map.put("resultMap", resultMap);
                    return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
                }

                // 循环行Row
                for (int rowNum = index; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow != null) {
                        if (StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(0))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(1)))) {
                            continue;
                        }
                        sysWhitePhone = new SysWhitePhone();
                        String name = ExcelUtils.getValue(hssfRow.getCell(0));//姓名
                        if (StringUtils.isBlank(name)) {
                            result = new HashMap<>();
                            result.put("reason", "姓名不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        sysWhitePhone.setName(name);
                        String delFlag = ExcelUtils.getValue(hssfRow.getCell(1));//删除状态，0否 1是
                        if (StringUtils.isBlank(delFlag)) {
                            result = new HashMap<>();
                            result.put("reason", "删除状态，0否 1是不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        sysWhitePhone.setDelFlag(delFlag);
                        sysWhitePhones.add(sysWhitePhone);
                    }
                }
                if (CommonUtils.isNotEmpty(sysWhitePhones)) {
                    resultMap.addAll(sysWhitePhoneService.importSysWhitePhoneExcel(sysWhitePhones));
                }
            }
            inputStream.close();
            Map<String, Object> map = new HashMap<>();
            map.put("resultMap", resultMap);
            return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.getResult(ResultInfo.ERROR);
        }
        return ResultUtils.getResult(ResultInfo.FAILED);
    }
}